const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin  = require("extract-text-webpack-plugin");
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
const StringReplacePlugin = require("string-replace-webpack-plugin");
const utils = require("./utils");
const fse = require("fs-extra");
const config = require("./config");
const fs = require("fs");
var babelrc = {};
try {
    babelrc =  JSON.parse(fs.readFileSync("./.babelrc").toString());
} catch (e) {
    console.error("error parse babelrc");
}

const PAGE = config.build.page;

const entry = {};

if (fs.existsSync(`./src/${PAGE}/component.js`)) {
    entry[PAGE+"-component"] = `./src/${PAGE}/component.js`;
}

if (fs.existsSync(`./src/${PAGE}/depend.js`)) {
    entry[PAGE+"-depend"] = `./src/${PAGE}/depend.js`;
}

if (fs.existsSync(`./src/${PAGE}/debug.js`)) {
    entry[PAGE+"-debug"] = `./src/${PAGE}/debug.js`;
}

if (fs.existsSync(`./src/${PAGE}/index.js`)) {
    entry[PAGE+"-index"] = `./src/${PAGE}/index.js`;
}

module.exports = {
    entry: entry,
    output: {
        path: config.build.assetsRoot,    
        filename: utils.assetsPath('js/[name].[chunkhash].js'),
        chunkFilename: utils.assetsPath(`js/${PAGE}/[id].[chunkhash].js`)
    },
    watch: false,
    module: {
        rules: [
            {
                test: /[\.js\.jsx\.es]$/,
                exclude: function(modulePath) {
                    return /node_modules/.test(modulePath) &&
                        !/node_modules\/andy-ui/.test(modulePath);
                },
                use: {
                  loader: 'babel-loader',
                  options: Object.assign({
                    presets: [
                       [
                            'env',
                            {
                                modules: false,
                                targets: {
                                    "browsers": ["ie >= 9"]
                                }
                            }
                       ]
                    ],
                  }, babelrc, {}),
                }
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                })
            },
            {
                test: /\.scss$/,
                use:  ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: [{
                        loader: "css-loader"
                    }, {
                        loader: "sass-loader",
                        options: {
                            includePaths: []
                        }
                    }, {
                        loader: "postcss-loader"
                    }]
                })
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
                loader: 'file-loader',
                query: {
                    name: 'static/fonts/[name]-[hash:8].[ext]'
                }
            },
            {
                test: /\.(png|gif|jpe?g|svg)$/,
                loader: 'url-loader',
                query: {
                    /*
                     *  limit=10000 ： 10kb
                     *  图片大小小于10kb 采用内联的形式，否则输出图片
                     * */
                    limit: 10000,
                    name: 'static/img/[name]-[hash:8].[ext]'
                }
            },
            {
                test: /\.(md)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '/static/md/[name][hash:8].[ext]'
                        }
                    }
                ]
            },
            {
                test: /\.html$/,
                loader: "html-loader"
            },
            {
                test: /index.html$/,
                use: [
                    {
                        loader: StringReplacePlugin.replace({
                            replacements: [
                            {
                                pattern: /@{DATE}/g,
                                replacement: function (match, p1, offset, string) {

                                    var d  = new Date();
                                    // var month = d.getMonth() + 1;
                                    // var version = d.getFullYear() + "-" + month + "-" + d.getDate() + "-" + d.getHours() + "-" + d.getMinutes();
                                    // var newname = `aunbox-service-worker-${version}.js`;

                                    // try {
                                    //     fse.copySync(`./src/${PAGE}/aunbox-service-worker.js`, `./dist/static/js/${PAGE}/${newname}`);
                                    //     console.log('success!')
                                    // } catch (err) {
                                    //     console.error(err)
                                    // }

                                    return d.valueOf();
                                }
                            }
                        ]})
                    }
                ]
            }            
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
             template: `src/${PAGE}/index.html`,
             filename: `${config.build.mainpageName}.html`,
             chunksSortMode: function (a, b) {  //alphabetical order
                var aname = a.names[0].split("-")[1];
                var bname = b.names[0].split("-")[1];              
                if (aname > bname) {
                  return 1;
                }
                if (aname < bname) {
                  return -1;
                }
                return 0;
            }
        }),
        new ExtractTextPlugin(config.build.assetsSubDirectory + "/css/[name]-[chunkhash:8].css"),
        new StringReplacePlugin(),
    ]
};